/*
 * Copyright By Peak3
 * Copyright By c336bf6ff03a756989bb456b5b5e3271228d43ed38461eb5cb5755d17a2fc9b8
 * All rights reserved.
 *
 * If you are not the intended user, you are hereby notified that any use, disclosure, copying, printing, forwarding or
 * dissemination of this property is strictly prohibited. If you have got this file in error, delete it from your system.
 */

package com.vv.tools.modules.auth.service;

import com.vv.tools.common.constant.sys.UserStatusEnum;
import com.vv.tools.modules.sys.entity.User;
import com.vv.tools.modules.sys.service.MenuService;
import com.vv.tools.modules.sys.service.UserService;

import jakarta.annotation.Resource;

import java.util.Set;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import static com.vv.tools.common.message.ResultEnum.AUTH_DISABLED;
import static com.vv.tools.common.message.ResultEnum.AUTH_USERNAME_NOT_FOUND;

/**
 * @author liwen
 */
@Slf4j
@Service
public class UserAuthService implements UserDetailsService {

    @Resource
    private UserService userService;

    @Resource
    private MenuService menuService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (StringUtils.isBlank(username)) {
            log.info("UserAuthService::用户不存在, username is blank");
            throw new UsernameNotFoundException(AUTH_USERNAME_NOT_FOUND.getMessage());
        }
        User user = userService.getByUsername(username);
        if (null == user) {
            log.info("UserAuthService::用户不存在, username: {}", username);
            throw new UsernameNotFoundException(AUTH_USERNAME_NOT_FOUND.getMessage());
        }
        if (UserStatusEnum.INVALID.getCode().equals(user.getStatus())) {
            log.info("UserAuthService::用户被禁用, username: {}", username);
            throw new LockedException(AUTH_DISABLED.getMessage());
        }
        // 权限
        Set<String> permission = menuService.getPermission(user.getId());
        return org.springframework.security.core.userdetails.User
            .withUsername(username)
            .password(user.getPassword())
            .authorities(permission.toArray(new String[0]))
            .build();
    }

}
